<?php

use Biz\cache\store\StoreCallAndReserve;
use Doraemon\model\Member\WxaPhoneModel;
use Doraemon\model\Phone;
use Doraemon\service\Login;
use Doraemon\service\Member\PhoneCrypto;
use Doraemon\tools\Crypt;
use Doraemon\model\Member\WxaModel;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\otherRedis;
use hhz\constant\basic\findPhoneScene;

/**
 * 获取用户的真实手机号(加密)返回给客户端
 *
 */
class GetUserPhoneAction extends ActionPlugin
{
    const DECRYPT_PHONE = 'magic_mirror_decrypt_getphone';
    const DEFAULT_RESERVE_LIMIT = 5;
    const DEFAULT_ERROR_CODE = self::CODE_ERROR_VIEW_TOSTA;

    public const USER_LEVEL = self::LEVEL_REGISTER;

    public const VALIDATOR_RULES = [
        'store_id' => 'require|integer',
    ];

    public function main()
    {
        $store_id = $this->params['store_id'];

        $user_uid = $this->uid;

        //判断该用户的拨打次数是否已经到达上线
        $user_call_info = StoreCallAndReserve::getUserCallStore($user_uid);

//        $constKey = redisKeys::KEY_B_OTHER_USER_STORE_CALL_;
//        $redis = new otherRedis($constKey);
//        $key = $constKey.$this->uid;
//        $user_call_info = $redis->smembers($key);

        if ($user_call_info) {
            $call_num = count($user_call_info);
            //如果数量满足,并且该门店id不再已拨打的id数组里的话,弹窗
            if ($call_num >= self::DEFAULT_RESERVE_LIMIT && !in_array($store_id, $user_call_info)) {
                throw new \Exception("抱歉，已超过当日拨打上限", self::DEFAULT_ERROR_CODE);
            }
        }

        //获取用户绑定的手机号
        /*$enc_phone = Phone::getUserPhone($user_uid);
        // 微信小程序特殊处理
        if (self::APPTYPE_STORE_MINIPROGRAM === $this->appType ) {
            if (!$enc_phone) {
                $enc_phone = WxaPhoneModel::getUserPhone($user_uid);
            }
            if (!$enc_phone) {
                $enc_phone = WxaModel::getUserPhone($user_uid);
            }
        }
        $decrypt_phone = null;
        if(!empty($enc_phone)){
            $decrypt_phone = PhoneCrypto::decrypt($enc_phone, self::DECRYPT_PHONE, PhoneCrypto::VERSIN);
        }
        */
        $decrypt_phone = Phone::getDecryptPhoneByUid($user_uid, findPhoneScene::STORE_VIRTUAL_GET_USERPHONE);
        if (!empty($decrypt_phone)) {
            //将客户端加密的手机号返回
            $crypt_phone = Crypt::encryptByPhone($decrypt_phone);
        }

        $data = [
            "uid" => $user_uid,
            "phone" => $crypt_phone,
        ];
        $this->setSuccess($data);
    }
}